package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Xiao
 * @date 2021/9/29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @Override
    public String sendMsgApi(String phone) {
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //SMSUtils.sendMessage(phone,code);
        return code;
    }

    /**
     * 获取当前登录的用户信息
     * @return
     */
    @Override
    public User getUserMsgApi() {
        return this.getById(BaseContext.getCurrentId());
    }

    /**
     * 登陆
     * @param phone
     * @param code
     * @param codeInSession
     * @return
     */
    @Override
    public User loginApi(String phone, String code, String codeInSession) {
        if (code.equals(codeInSession)) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = this.getOne(wrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setName("瑞吉用户" + IdWorker.getId());
                this.save(user);
                log.info("注册新用户 --> phone:{}", phone);
            }
            return user;
        }
        return null;
    }
}
